package org.example.cardgame.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

public class ImageToBase64 {

    public static String convertImageToBase64(InputStream inputStream) throws IOException {
        // 替代 readAllBytes() 的方法
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] tempBuffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(tempBuffer)) != -1) {
            buffer.write(tempBuffer, 0, bytesRead);
        }
        byte[] imageBytes = buffer.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    public static void main(String[] args) {
        getBase64For("download.gif");
    }

    public static String getBase64For(String image) {
        try {
            ClassLoader classLoader = ImageToBase64.class.getClassLoader();
            try (InputStream inputStream = classLoader.getResourceAsStream(image)) {
                if (inputStream != null) {
                    System.out.println("文件已找到: " + image);
                    String base64Image = convertImageToBase64(inputStream);
                    System.out.println(base64Image);
                    return "data:image/jpeg;base64," + base64Image;
                } else {
                    System.out.println("文件不存在: " + image);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}
